package org.hive.utils
{
	/**
	 * 
	 * @author jovanalleyne
	 * 
	 * @description This class is designed to parse and transform HTML return 
	 * by using Javascript and adapt it to work with ActionScript TextField.
	 * Most commonly the issue has been the stripping of quotes by IE (only 
	 * versions 6 & 7 have been tested). As a result of unquoted attributes like
	 * id=12 your TextField will not display any text using the htmlText method.
	 * 
	 */	
	public class FLHTML
	{
		
		/**
		 * @private const
		 * Regular Expression to find tags containing attributes 
		 * with no quotes.
		 */		
		private static const TAG_EXP:RegExp = new RegExp( /<[a-zA-Z0-9_]+(?: (?:[a-zA-Z0-9_]+=)(?:['|"]?[#a-zA-Z0-9_\.: \/]+['|"]?))+>/ig );
		
		/**
		 * @private const
		 * Regular Expression to find attributes in tags and break 
		 * them into groups.
		 */		
		private static const ATTRIBUTE_EXP:RegExp = new RegExp( /([a-zA-Z0-9_]+=)([#a-zA-Z0-9_\.:\/]+)/ig );
		
		/***********************************
		 * CONSTRUCTOR
		 **********************************/
		public function FLHTML()
		{
		}
		
		/**
		 * 
		 * @param p_value
		 * @return String containing HTML tag adapted to be compatible with ActionScript's
		 * TextField. As more compatibility differences arise, methods to transform this HTML
		 * into a String that ActionScript can render with the htmlText method of TextField
		 * can be added to this method.  
		 *   
		 * 
		 */		
		public static function adapt( p_value:String ):String
		{	
			var r:Object = TAG_EXP.exec(p_value);
			while (r != null) 
			{
				// add quotes to attributes
				p_value = p_value.replace( r[0], quoteAttributes( r[0] ) );
				// continue checking
				r = TAG_EXP.exec( p_value );
			}
			return p_value;
		}

		/**
		 * 
		 * @param p_tag
		 * @return String containing HTML tag properly quoted for use with TextField.
		 * 
		 */		
		private static function quoteAttributes( p_tag:String ):String
		{
			var a:Object = ATTRIBUTE_EXP.exec( p_tag );
			while ( a != null ){
				p_tag = String(p_tag).replace( a[0], a[1] + "\"" + a[2] + "\"" );
				a = ATTRIBUTE_EXP.exec( p_tag );
			}
			return p_tag;
		}
	
	}
}